//
//  OATenderInfoVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/6.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

import WebKit
import Kingfisher
import AVFoundation
//  领导查询  -  招标（原料） 药品   物流

 // 竞拍猪业    竞拍成交


// 饲料 -  招标进度
// 猪场   竞拍

class OATenderInfoVC: UIViewController,getDepositRemainable,approvable {
    
    lazy var tbinfoView: TbInfoNewView = {
        
        var v = TbInfoNewView()
        return v
        
        
    }()
   
    var jpTitleView:TitleChujiaImgView!
    lazy var timeflagView:ZyaTimeFlagView = {
        let v = ZyaTimeFlagView()
        return v
    }()
    var depositRemain = 0.0
    var processid = ""
    var voccd = ""
    var enterType = EnterType.none
    var todoType = TodoType.normal
    var timerAvaliable = false
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        return tableView
    }()
    
    var webHeight:Double?
    var imgHeight:Double?
    
    var headView = UIView()
    
    
    lazy var zbInstructions:UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.systemFont(ofSize: 15)
        lab.backgroundColor = .white
        lab.textAlignment = .center
        lab.text = "招标说明"
        return lab
    }()
    lazy var zbLine:UIView = {
        let view:UIView = UIView()
        view.backgroundColor = #colorLiteral(red: 0.7764705882, green: 0.7764705882, blue: 0.7843137255, alpha: 1)
        
        return view
    }()
    var btnflag = "1"
    
    var webV: WKWebView = {
        let web = WKWebView()
        return web
    }()
    
    lazy var bottomView: UIView = {
        let view:UIView = UIView()
        let line = UIView(frame: CGRect(x:0,y:0,width: KSGlobal.screenW,height: 1))
        line.backgroundColor = #colorLiteral(red: 0.6039215686, green: 0.6039215686, blue: 0.6039215686, alpha: 1)
        view.addSubview(line)
        return view
    }()
    
    private var zbFiles = [ZbFile]()
    
    lazy var btn_mark:OpButton = {
        var btn1 = OpButton()
        btn1.setTitle("收藏", for: .normal)
        btn1.addTarget(self, action: #selector(markAction), for: .touchUpInside)
        if let shoucang = UIImage(named:"shoucang") {
            btn1.setImage(shoucang, for: .normal)
        }
        return btn1
    }()
    
    lazy var btn_down:OpButton = {
        var btn_down = OpButton()
        btn_down.setTitle("下载", for: .normal)
        btn_down.addTarget(self, action: #selector(downloadAction), for: .touchUpInside)
        if let xiazai = UIImage(named:"xiazai") {
            btn_down.setImage(xiazai, for: .normal)
        }
        return btn_down
    }()
    lazy var btn_feedback:OpButton = {
        var btn_down = OpButton()
        btn_down.setTitle("反馈", for: .normal)
        btn_down.addTarget(self, action: #selector(feedbackAction), for: .touchUpInside)
        if let xiazai = UIImage(named:"feedback1") {
            btn_down.setImage(xiazai, for: .normal)
        }
        return btn_down
    }()
    lazy var btn_call:OpButton = {
        
        var btn_call = OpButton()
        btn_call.setTitle("电话", for: .normal)
        btn_call.addTarget(self, action: #selector(phoneAction(sender:)), for: .touchUpInside)
        if let phone = UIImage(named:"phone") {
            btn_call.setImage(phone, for: .normal)
        }
        return btn_call
    }()
    lazy var btn_tb:ActionButton = {
        var btn_tb = ActionButton()
        return btn_tb
    }()
    var idkey:String = ""
    var originalMark:Int?
    var innerType:ZTBInnerType?
    
    private var one = ZtbContentModel(JSON:["":""])!
    private let helper = ZyaTenderHelper()
    
    
    
    var listType = TBandJPType.TB
    
    
    
    var timer4Countdown :Timer?
    
    
    
    init(listType:TBandJPType) {
        super.init(nibName: nil, bundle: nil)
        self.listType = listType
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tickDown(){
        
        if let endTime = self.one.zEndDate {
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            
            let dateFormatter2 = DateFormatter()
            dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
            let dateFormatter3 = DateFormatter()
            dateFormatter3.dateFormat = "yyyy-MM-dd"
            
            var endDDD = Date()
            if let endD = dateFormatter.date(from: endTime) {
                endDDD = endD
            }
            
            if let endD2 = dateFormatter2.date(from: endTime) {
                endDDD = endD2
            }
            
            if let endD3 = dateFormatter3.date(from: endTime) {
                endDDD = endD3
            }
            
            let timeNumber = Int(endDDD.timeIntervalSince1970-dateFormatter.date(from: Date.nowTimeToSecond)!.timeIntervalSince1970)
            if timeNumber > 0 {
                print("倒计时xxx" + Date.getHHMMSSFormSS(seconds: timeNumber))
                if self.timerAvaliable {
                    self.timeflagView.setTimeFlagInfo(status: "进行中", countDown: "距结束 " + Date.getHHMMSSFormSS(seconds: timeNumber), model: self.one)
 
                }
            } else {
                if self.timerAvaliable {
                    self.timerAvaliable = false
                    self.pageNetwork()
                }
                
            }
            
            
        }
        
        
        
    }
    
    var isTranslucent_ori:Bool? // 本控件需要操作，但是又不希望影响到其他的控件
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 收藏按钮状态在页面内被改变，退出时检测到做收藏接口改变操作
        if self.one.ztbMark != self.originalMark {
            self.helper.setRecordMark(z_record_id:self.idkey,z_mark:self.one.ztbMark.unwrap,z_type:self.listType == .TB ? "zhaobiao" : "jingpai")
            
        }
        if let trat = isTranslucent_ori {
            self.navigationController?.navigationBar.isTranslucent = trat
        }
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if timer4Countdown.isSome {
            timer4Countdown!.invalidate()
            timer4Countdown = nil
        }
        
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.timer4Countdown.isNone {
            self.timer4Countdown = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(self.tickDown), userInfo:nil, repeats:true)
        }
        // 防止位置会下移一个导航的高度
        isTranslucent_ori = self.navigationController?.navigationBar.isTranslucent
        self.navigationController?.navigationBar.isTranslucent = true
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if listType == .JP {
            jpTitleView = TitleChujiaImgView( withImg: true)

        } else {
            jpTitleView = TitleChujiaImgView( withImg: false)
      
        }
        
        self.title = "详情"
        self.view.backgroundColor = .white
        
        self.helper.configSubView(superV:self,tableV:tableView,bottomV:bottomView)
  
            headView.addSubview(timeflagView)
        timeflagView.frame = CGRect(x:0,y:0,width: self.view.frame.width,height: 35)

        headView.addSubview(jpTitleView)

          
         
        
        
        headView.addSubview(tbinfoView)
        headView.addSubview(zbLine)
        headView.addSubview(zbInstructions)
        headView.isUserInteractionEnabled = true
        headView.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height: 600)
        self.tableView.tableHeaderView = headView
        
    
            zbInstructions.text = "报价说明"
        timeflagView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.top.equalTo(headView)
            make.height.equalTo(35)
        }
            jpTitleView.snp.makeConstraints { (make) in
                make.left.equalTo(self.view)
                make.right.equalTo(self.view)
                make.top.equalTo(timeflagView.snp.bottom)
            }
            
      
        
        tbinfoView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
           
                make.top.equalTo(jpTitleView.snp.bottom)
             
            
            
        }
        
        zbLine.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.right.equalTo(self.view).offset(-10)
            make.top.equalTo(self.tbinfoView.snp.bottom).offset(20)
            make.height.equalTo(1)
        }
        
        zbInstructions.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.width.equalTo(110)
            make.top.equalTo(self.tbinfoView.snp.bottom).offset(5)
            make.height.equalTo(30)
        }
        
        headView.addSubview(webV)
        webV.snp.makeConstraints { (make) in
            make.left.equalTo(zbLine)
            make.right.equalTo(zbLine)
            make.height.equalTo(30)
            make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
        }
        
        
        
        webV.navigationDelegate = self
        
        tableView.tableFooterView = UIView()
        
        
        
        self.configApproveUI(enterType: self.enterType, todotype: self.todoType, processid: processid, voc_cd: voccd, vou_id: idkey, task_id: self.taskidFromTodoList.unwrap,vc: self) { (checkView) in
            self.tableView.tableFooterView = checkView
            self.tableView.reloadData()
        }
        
        self.pageNetwork()
        
        NotificationCenter.default.addObserver(self, selector: #selector(pageNetwork), name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
        
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func pageNetwork() {
        
        
        KSNetwork.shared.doRequest(self.helper.getZBInfoAPI(listType:self.listType,id_key:idkey)) { (data:BaseResult<ZtbContentModel>) in
            if data.flag == TRUE {
                // 完成掉推送跳转的任务了
                waitGo2Model = WaitModel(complete: true, type: 0 , id: "")
                
                
                if let info = data.infoObjCombine {
                    self.one = info
                    self.jpTitleView.showBannerImg(one: info)
                    
                    let paraph = NSMutableParagraphStyle()
                    //将行间距设置为28
                    paraph.lineSpacing = 9
                    //样式属性集合
                    let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17),
                                      NSAttributedString.Key.paragraphStyle: paraph]
                    
                    self.jpTitleView.titleLab.text = info.zTitle.unwrap
                    self.jpTitleView.subTitleLab.text = "\(intTran(info.zBidCount))次出价"
                    
//                    if  let imageUrl = URL(string:"\(self.one.zMainUrl.unwrap)?sid=\(self.one.sid.unwrap)") {
//                        let resource = KF.ImageResource(downloadURL: imageUrl)
//                        self.jpTitleView.imgbg.kf.setImage(with: resource, placeholder: UIImage(named:"defaultImg_content"))
//                        
//                        
//                        
//                    }
                    
                    self.jpTitleView.setChujiaShow(title: self.one.zTitle.unwrap, count: self.one.zBidCount.unwrap, price: self.one.zPrice.unwrap,unit: self.one.zUnitNm.unwrap, rank: self.one.zPriceRank.unwrap,z_end_price_rank: "",z_parallel: "")
                    
//                    
//                    if info.zPriceRank.unwrap.isEmpty {
//                        self.jpTitleView.hiddenChujia()
//                    } else {
//                        self.jpTitleView.showChujia()
//                        self.jpTitleView.chujiaLab.text = info.zPriceRank.unwrap
//                    }
//                    
                   
                    
                    
                    
                    let btnName = getZBJPStatus(listType: self.listType, auditmark: intTran(info.zAuditMark), status: intTran(info.zStatus), tbType: self.innerType!)
                    
                    var timeTipStr:String = ""
                    if btnName == "未开始" {
                        self.timerAvaliable = false
                        timeTipStr = "\(info.zBeginDate.unwrap)开始"
                    } else if  btnName == "进行中" {
                        self.timerAvaliable = true
                        if self.timer4Countdown.isNone {
                            self.timer4Countdown = Timer.scheduledTimer(timeInterval:1, target:self,selector:#selector(self.tickDown), userInfo:nil, repeats:true)
                        }
                    } else  {
                        self.timerAvaliable = false
                        timeTipStr = "\(info.zEndDate.unwrap)结束"
                    }
                    self.timeflagView.setTimeFlagInfo(status: btnName, countDown: timeTipStr, model: self.one)
                    
                    /// 招投标或者为你推荐  可以投标
                    if (self.innerType == .zbListKHW || self.innerType == .recommendKHW || self.innerType == .jpListKHW) && (USERINFO.usrid.unwrap != info.zStaffId.unwrap) {
                        
                        
              
                        
                        if info.zAuditMark.unwrap == "0" || info.zAuditMark.unwrap == "2" || info.zAuditMark.unwrap == "9" {
                            self.configZBBottom(listType: self.listType,true,btnName,getRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                        } else if info.zAuditMark.unwrap == "1" {
                            if info.zStatus.unwrap == "0" {
                                self.configZBBottom(listType: self.listType,true,"未开始",getRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                            } else if info.zStatus.unwrap == "1" || info.zStatus.unwrap == "3" {
                                self.configZBBottom(listType: self.listType,true,"已结束",getRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                            } else if info.zStatus.unwrap == "2" {
                                
                                // 查询现有保证金余量
                                self.getDepositValue { (flag,value) in
                                    if flag {
                                        self.depositRemain = doubleTran(value)
                                        var showName = ""
                                        var judgeID = ""
                                        if self.innerType == .jpListKHW {
                                            showName = "销售招标"
                                            judgeID = info.zBidId.unwrap
                                        } else {
                                            showName = "投标"
                                            judgeID = info.zTbId.unwrap
                                        }
                                        if self.depositRemain >= info.zDepositMoney.doubleWrap { // （保证金足够）
                                            
                                            if judgeID.isEmpty {
                                                // 没id 说明是新的
                                                self.configZBBottom(listType: self.listType,true,showName,getRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                                            } else {
                                                // 有id 说明是投过的，显示编辑
                                                self.configZBBottom(listType: self.listType,true,"编辑",getRest4Show(max: info.zMaxBidNo.unwrap, rest: info.zRestBidNo.unwrap))
                                            }
                                        } else {
                                            // 保证金不足
                                            if let remain = info.zRemainTry {
                                                if remain == "0" {
                                                    self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                                } else {
                                                    self.configZBBottom(listType: self.listType,true,"试投","(剩余\(remain)次)",id:judgeID)
                                                }
                                            } else {
                                                self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                            }
                                            
                                            
                                            
                                            
                                            
                                        }
                                    } else { // 错误，一般为未开通保证金账户
                                        self.configZBBottom(listType: self.listType,true,"缴纳保证金","")
                                    }
                                    
                                }
                                
                                
                                
                                
                            } else {
                                self.configZBBottom(listType: self.listType,false)
                            }
                        } else {
                            self.configZBBottom(listType: self.listType,false)
                        }
                        
                    } else { // 其他不能投标
                        self.configZBBottom(listType: self.listType,false)
                    }
                   
                    
//                    self.tbinfoView.contentStr = self.helper.getContentStr(listType: self.listType, info: info)
                    if self.listType == .JP {
                        self.tbinfoView.contentStr = info.jpInfo.unwrap
                    } else {
                        self.tbinfoView.contentStr = info.zbInfo.unwrap
                    }
                 
//                    return info.zbInfo.unwrap.replacingOccurrences(of: "#", with: "\n")
//               
//                    return info.jpInfo.unwrap.replacingOccurrences(of: "#", with: "\n")
               
                    
                    self.tbinfoView.ks_height = self.tbinfoView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
                    self.originalMark = info.ztbMark
                    
                    if info.zInvited.unwrap == "1" {
                        // 如果有邀标标志，展示邀标按钮
                        self.navigationItem.rightBarButtonItem = self.helper.configRightItem4Tender(listType:self.listType) {
                            self.helper.getInviteListAction(listType: self.listType, fromVC: self, z_zb_id: self.one.idKey.unwrap)
                        }
 
                        
                    }
                    
                    
                    self.webV.loadHTMLString(adaptHtml(info.zContent.unwrap), baseURL: nil)
                    let imgNm = info.ztbMark.intWrap == 1 ? "shoucang_red" : "shoucang"
                    self.btn_mark.setImage(UIImage(named: imgNm), for: .normal)
                    
                    
                    if let files = info.zbFile {
                        
                        
                        self.zbFiles = files
                        let hasPictureArr = self.zbFiles.filter{ $0.zType == "0" }
                        
                        // 创建调度组
                        let workingGroup = DispatchGroup()
                        
                        for i in 0..<self.zbFiles.count {
                            
                            if self.zbFiles[i].zType == "2" { // 视频
                                
                                let ggUrl = self.zbFiles[i].zPicUrl.unwrap.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                                let  vedioImg = self.getFirstFrame(url: "\(ggUrl)")
                                self.zbFiles[i].imageV = vedioImg
                                
                            } else if self.zbFiles[i].zType == "0" { // 图片
                                
                                
                                let btn = UIImageView()
                                btn.contentMode = .scaleAspectFit
                                btn.tag = i
                                let ggUrl = self.zbFiles[i].zPicUrl.unwrap.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                                if  let imageUrl = URL(string:"\(ggUrl)") {
                                    let resource = KF.ImageResource(downloadURL: imageUrl)
                                    // 入组
                                    workingGroup.enter()
                                    btn.kf.setImage(with: resource, placeholder: UIImage(named:"defaultImg_content"),completionHandler: {
                                        (kfresult:Result<RetrieveImageResult, KingfisherError>) in
                                        workingGroup.leave()
                                    })
                                } else {
                                    btn.image = UIImage(named:"defaultImg_content")
                                }
                                
                                self.zbFiles[i].imageV = btn
                                
                            } else {
                                let btn = FileButton()
                                btn.tag = i
                                btn.setTitle(files[i].zName, for: .normal)
                                btn.addTarget(self, action: #selector(self.btnAction(sender:)), for: .touchUpInside)
                                self.zbFiles[i].fileBtn = btn
                            }
                            
                        }
                        if hasPictureArr.count == 0 {
                            self.preMakeCon()
                        }
                        
                        // 调度组里的任务都执行完毕
                        workingGroup.notify(queue: .main) {
                            
                            self.preMakeCon()
                        }
                        
                        
                    }
                    
                }
                
                
                
            } else {
                
            }
        }
        
    }
    func preMakeCon() {
        self.makeImgVedioConstr()
        self.showFinalheaderHeight()
    }
    
    // 给图片和视频布局
    func makeImgVedioConstr() {
        self.imgHeight = 0
        //        for subV in self.headView.subviews {
        //            if subV.isMember(of: FileButton.self) || subV.isMember(of: UIImageView.self) {
        //                subV.removeFromSuperview()
        //            }
        //        }
        let fileArr = self.zbFiles.filter{ $0.fileBtn.isSome }
        let imageArr = self.zbFiles.filter{ $0.imageV.isSome }
        
        for i in 0..<fileArr.count {
            let fileBtn = fileArr[i].fileBtn!
            
            self.headView.addSubview(fileBtn)
            self.imgHeight! += 30
            fileBtn.snp.makeConstraints { (make) in
                if i == 0 {
                    make.top.equalTo(self.webV.snp.bottom).offset(6)
                } else {
                    make.top.equalTo(fileArr[i - 1].fileBtn!.snp.bottom).offset(6)
                }
                make.width.equalTo(KSGlobal.screenW)
                make.height.equalTo(30)
                make.centerX.equalTo(self.headView)
            }
        }
        for i in 0..<imageArr.count {
            let imageV = imageArr[i].imageV!
            self.headView.addSubview(imageV)
            if imageArr[i].zType == "2" {
                imageV.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer()
                tap.numberOfTapsRequired = 1
                tap.addTap { [unowned self,i]  _ in
                    let file = imageArr[i]
                    let cwebV = CommonWebController()
                    let str1 = "\(file.zPicUrl.unwrap)"
                    cwebV.reportUrl = str1
                    cwebV.title = file.zName.unwrap
                    self.navigationController?.pushViewController(cwebV, animated: true)
                    
                }
                
                imageV.addGestureRecognizer(tap)
                
                let v_start = UIImageView()
                v_start.image = UIImage(named: "vedio_start")
                imageV.addSubview(v_start)
                v_start.snp.makeConstraints { make in
                    make.bottom.right.equalTo(imageV).offset(-10)
                    make.width.equalTo(50)
                    make.height.equalTo(50)
                }
            }
            var scale:CGFloat = 1
            if let imggg = imageV.image {
                scale = imggg.size.height / imggg.size.width
            }
            if scale > 2.5 {
                scale = 2.5 // 控制一下比例最大值，防止非常长
            }
            
            self.imgHeight! += Double(KSGlobal.screenW * scale)
            imageV.snp.makeConstraints { (make) in
                if i == 0 {
                    if fileArr.count == 0 {
                        make.top.equalTo(self.webV.snp.bottom).offset(6)
                    } else {
                        make.top.equalTo(fileArr[fileArr.count - 1].fileBtn!.snp.bottom).offset(6)
                    }
                } else {
                    make.top.equalTo(imageArr[i - 1].imageV!.snp.bottom).offset(6)
                }
                make.height.equalTo(KSGlobal.screenW * scale)
                make.width.equalTo(KSGlobal.screenW)
                make.centerX.equalTo(self.headView)
                
            }
        }
        
    }
    
    
    /// withOpBtn 是否带右侧操作按钮
    func configZBBottom(listType:TBandJPType,_ withOpBtn:Bool,_ btnName:String? = "",_ cishuDesc:String? = "",id:String = "") {
        if btn_tb.superview.isSome { // 重置状态先移除操作按钮
            btn_tb.removeFromSuperview()
        }
        if btn_mark.superview.isSome { // 重置状态先移除操作按钮
            btn_mark.removeFromSuperview()
        }
        if btn_down.superview.isSome { // 重置状态先移除操作按钮
            btn_down.removeFromSuperview()
        }
        if btn_feedback.superview.isSome { // 重置状态先移除操作按钮
            btn_feedback.removeFromSuperview()
        }
        if btn_call.superview.isSome { // 重置状态先移除操作按钮
            btn_call.removeFromSuperview()
        }
        var chirds = [(UIButton,CGSize)]()
        
        let opWidth:CGFloat = 45
        let tbWidth:CGFloat = withOpBtn ? 130 : 0
        
        
        bottomView.addSubview(btn_mark)
        chirds.append((btn_mark,CGSize(width: opWidth, height: 54)))
        
        if listType == .TB {
            bottomView.addSubview(btn_down)
            chirds.append((btn_down,CGSize(width: opWidth, height: 54)))
        } else {
            bottomView.addSubview(btn_feedback)
            chirds.append((btn_feedback,CGSize(width: opWidth, height: 54)))
        }
        
        bottomView.addSubview(btn_call)
        chirds.append((btn_call,CGSize(width: opWidth, height: 54)))
        // 要求带按钮且不是访客
        if withOpBtn && !self.helper.isFangke() && btnName.unwrap != "" {
            bottomView.addSubview(btn_tb)
            chirds.append((btn_tb,CGSize(width: tbWidth, height: 40)))
        }
        
        
        // 控件间距
        let subWidths = chirds.compactMap{ $0.1.width }.reduce(0, +)
        let marginx = (KSGlobal.screenW - subWidths) / CGFloat(chirds.count + 1)
        var lastX = marginx
        for one in chirds {
            one.0.frame.size = one.1
            one.0.ks_x = lastX
            lastX = lastX + one.1.width + marginx
            one.0.ks_centerY = 30
        }
        
        
        if btnName.unwrap == "进行中" || btnName.unwrap == "投标" {
            btn_tb.setTitle("投标\(cishuDesc!)", for: .normal)
            btn_tb.tag = 101
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        } else if  btnName.unwrap == "销售招标" {
            btn_tb.setTitle("竞拍\(cishuDesc!)", for: .normal)
            btn_tb.tag = 102
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        }  else if btnName.unwrap == "编辑" {
            btn_tb.setTitle("编辑\(cishuDesc!)", for: .normal)
            btn_tb.tag = 103
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
            
        } else if btnName.unwrap == "缴纳保证金" {
            btn_tb.setTitle("缴纳保证金", for: .normal)
            btn_tb.tag = 104
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        } else if btnName.unwrap == "试投" {
            
            if self.listType == .TB {
                btn_tb.setTitle("试投\(cishuDesc!)", for: .normal)
                btn_tb.tag = id.isEmpty ?  101 : 103
            } else {
                btn_tb.setTitle("试拍\(cishuDesc!)", for: .normal)
                btn_tb.tag = id.isEmpty ? 102 : 103
            }
            btn_tb.addTarget(self, action: #selector(clickAction(sender:)), for: .touchUpInside)
        }  else {
            btn_tb.setTitle(btnName.unwrap, for: .normal)
        }
        
        
        
    }
    
    
    @objc func clickAction(sender:UIButton) {
        
        guard !self.helper.isFangke() else {
            KSToast("访客无权限")
            return
        }
        
        switch sender.tag {
        case 101,102:
            let result =  userDefault.value(forKey: USERINFO.usrid.unwrap + self.idkey) as? String
            if result == "1" { // 阅读过协议了
                
                self.helper.go2TenderTbController(listType: self.listType,controller: self, z_zb_id: self.idkey,z_bid_id: self.one.zBidId.unwrap, excuteType: .add,model:self.one) {
                    self.pageNetwork()
                }
                
            } else {
                
//                let vc = KhwAgreementController.initWithNav(z_zb_id: self.idkey) { passflag in
//
//                    if passflag {
//                        self.helper.go2TenderTbController(listType: self.listType,controller: self, z_zb_id: self.idkey,z_bid_id: self.one.zBidId.unwrap, excuteType: .add,model:self.one) {
//                            self.pageNetwork()
//                        }
//                    }
//
//
//                }
//                self.present_FullScreen(to: vc)
                
            }
        case 103:
            
            self.helper.go2TenderTbController(listType: self.listType, controller:self,z_tb_id:one.zTbId.unwrap,z_zb_id:"",z_bid_id: self.one.zBidId.unwrap,excuteType:.fix,model:self.one) {
                self.pageNetwork()
            }
        case 104:
            let result =  userDefault.value(forKey: USERINFO.usrid.unwrap + self.idkey) as? String
            if result == "1" { // 阅读过协议了
                
                self.helper.go2DepositController(controller: self)
                
            } else {
                
//                let vc = KhwAgreementController.initWithNav(z_zb_id: self.idkey) { passflag in
//
//                    if passflag {
//                        self.helper.go2DepositController(controller: self)
//                    }
//
//                }
//                self.present_FullScreen(to: vc)
                
            }
            
        default:
            break
        }
    }
    
    
    
    
    @objc func btnAction(sender:UIButton) {
        let file = self.zbFiles[sender.tag]
        let cwebV = CommonWebController()
        let str1 = "\(file.zPicUrl.unwrap)"
        cwebV.reportUrl = str1
        cwebV.title = file.zPicUrl.unwrap
        self.navigationController?.pushViewController(cwebV, animated: true)
        
    }
    @objc func feedbackAction() {
        self.helper.go2FeedbackForm(zZbId: self.one.idKey.unwrap, zZbNo: self.one.zRecordNo.unwrap, zTitle: self.one.zTitle.unwrap,controller: self)
 
        
    }
    
    @objc func downloadAction() {
        
        self.helper.downloadFiles(zbFiles: self.zbFiles)
        
        
    }
    @objc func markAction() {
        if self.one.ztbMark.intWrap == 1 {
            self.one.ztbMark = 0
            self.btn_mark.setImage(UIImage(named: "shoucang"), for: .normal)
        } else {
            self.one.ztbMark = 1
            self.btn_mark.setImage(UIImage(named: "shoucang_red"), for: .normal)
        }
        
        
    }
    
    @objc func phoneAction(sender:UIButton) {
        
        
        if self.btnflag == "1" {
            
            self.btnflag = "0"
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                self.btnflag = "1"
            }
            
            
            let phone = "tel://" + one.zTel.unwrap
            if UIApplication.shared.canOpenURL(URL(string: phone)!) {
                
                UIApplication.shared.open(URL(string: phone)!, options: [:], completionHandler: { result in
                })
                
            } else {
                KSToast("电话错误")
            }
            
        }
        
        
        
    }
    func getFirstFrame(url:String) -> UIImageView {
        let thumb = UIImageView()
        if let urlx = URL.init(string: url) {
            let asset = AVURLAsset.init(url: urlx, options: nil)
            let gen = AVAssetImageGenerator.init(asset: asset)
            gen.appliesPreferredTrackTransform = true
            let time = CMTimeMake(value: Int64(0.0), timescale: 1)
            var actualTime : CMTime = CMTimeMake(value: Int64(0.0), timescale: 0)
            do {
                let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
                thumb.image = UIImage.init(cgImage: image)
            } catch  {
                thumb.image = UIImage(named:"defaultImg_content")
            }
        } else {
            thumb.image = UIImage(named:"defaultImg_content")
        }
        return thumb
    }
}

extension OATenderInfoVC: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var webheightx = 0.0
        self.webV.evaluateJavaScript("document.documentElement.clientHeight") { [unowned self] (result, error) in
            
            if let tempHeight: Double = result as? Double {
                webheightx = tempHeight
            }
            DispatchQueue.main.async { [unowned self] in
                
                let endRect = dealwithHeight(height: webheightx, rect: self.webV.frame)
                self.webV.snp.remakeConstraints { (make) in
                    make.left.equalTo(self.zbLine)
                    make.right.equalTo(self.zbLine)
                    make.height.equalTo(webheightx)
                    make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
                }
                self.webHeight = webheightx
                self.showFinalheaderHeight()
                
            }
        }
        
        
        
    }
    
    func showFinalheaderHeight() {
        
        if let wh = self.webHeight,let ih = self.imgHeight {
            
            self.headView.ks_height = self.helper.getHeaderHeight(webheight: wh,imgHeight:ih)
            self.tableView.reloadData()
        }
    }
    
}



/// 最大为0 时 ，不显示剩余次数，否则显示 剩余次数
func getRest4Show(max:String,rest:String) -> String {
    if max == "0" {  // 无限次，随便保存，不用显示
        return ""
    } else {  // 有限次， 可以保存
        return "(剩余\(rest)次)"
    } // 次数用完了
}
// 用最大次数和剩余次数判断是否可操作
func getRest4Judge(max:String,rest:String) -> Bool {
    if max == "0" {
        return true
    } else if rest != "0" {
        return true
    } else {
        return false
    }
}





class OpButton:UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitleColor(.darkGray, for: .normal)
        self.titleLabel?.textAlignment = .center
        self.titleLabel?.font = UIFont.systemFont(ofSize: 13)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let width_r = self.frame.width * 0.7
        // 设置imageView
        imageView?.frame = CGRect(x: (self.frame.size.width - width_r)/2 , y: 0, width: width_r, height: width_r)
        // 设置title
        titleLabel?.frame = CGRect(x: 0 , y: self.frame.height/2, width: self.frame.width, height: self.frame.height/2)
        
        
    }
}

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}


class ActionButton:UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        self.layer.cornerRadius = 20
        self.setTitleColor(.white, for: .normal)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func setTitle(_ title: String?, for state: UIControl.State) {
        super.setTitle(title, for: state)
        if title.unwrap.count > 8 {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        } else if title.unwrap.count > 5 {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        } else {
            self.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            
        }
        
        if title.unwrap == "已结束" || title.unwrap == "未开始" {
            self.backgroundColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        } else if title.unwrap.contains("编辑") {
            self.backgroundColor = .blue
        } else if title.unwrap.contains("试") {
            self.backgroundColor = Theme.primaryColor()
        } else {
            self.backgroundColor = .red
        }
        
        
    }
}
func getZBJPStatus(listType:TBandJPType,auditmark:Int,status:Int,tbType:ZTBInnerType) -> String {
    
    
    var btnName = ""
    if tbType == .tbMytbKHW {
//        if status == 1 {
//            btnName =  "已开标"
//        } else if status == 0 {
//            btnName =  "未中标"
//        } else {
//            btnName =  "已放弃"
//        }
        
        switch status {
        case 0:
            btnName = "未开始"
//            self.setBtnStyle(color: UIColor(kshex: tenderBlue))
        case 1:
            btnName = listType == .TB ? "已开标" : "已成交"
//            self.setBtnStyle(color: UIColor(kshex: tenderGreen))
        case 2:
            btnName = "进行中"
//            self.setBtnStyle(color: .red)

        case 3:
            btnName = "已结束"
//            self.setBtnStyle(color: UIColor.lightGray)
        case 4:
            btnName = listType == .TB ? "已流标" : "已流拍"
//            self.setBtnStyle(color: UIColor.lightGray)
        default:
            print("33")
        }
        
        
    } else if tbType == .tbRecordKHW {
        if status == 1 {
            btnName =  "已中标"
        } else if status == 0 {
            btnName =  "未中标"
        } else {
            btnName =  "已放弃"
        }
    } else if tbType == .chujiaRecordKHW {
               if status == 1 {
                   btnName =  "已成交"

               } else if status == 0 {
                   btnName =  "未成交"
               } else {
                   btnName =  "已结束"
               }
    } else if tbType == .zbAnnouncementKHW {
        btnName = "已开标"
    } else if tbType == .chujiaRecordJP {
        btnName = "已出价"
    } else if tbType == .cjAnnouncementKHW {
        btnName = "已开拍"
    } else {
        if auditmark == 1 {
            switch status {
            case 0:
                btnName = "未开始"
            case 1:
                btnName = listType == .TB ? "已开标" : "已成交"
            case 2:
                btnName = "进行中"

            case 3:
                btnName = "已结束"
            case 4:
                btnName = listType == .TB ? "已流标" : "已流拍"
            default:
                print("33")
            }
        } else if auditmark == 0 {
            btnName = "未提交"
        } else if auditmark == 2 {
            btnName = "已退回"
        } else if auditmark == 9 {
            btnName = "已提交"
        }
    }
    return btnName
}
